package cn.crex1.springboot.securitydemo.controller;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class BrowserSecurityController {
    //判断引发跳转的是否是html
    // 用RequestCache拿到引发跳转的请求
    private RequestCache requestCache = new HttpSessionRequestCache();

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 当需要身份认证时，跳转到这里
     *
     * @param request
     * @param response
     * @return SimpleResponse
     * @throws IOException
     */
    @RequestMapping("/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED) //返回状态码
    public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //拿到引发跳转的请求
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if (savedRequest != null) {
            //引发跳转请求的url
            String targetUrl = savedRequest.getRedirectUrl();
            System.out.println("引发跳转的请求时： " + targetUrl);
            if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) {
                //判断引发跳转的请求是否是以.html结尾 //跳转到登录页

                /**
                 * request
                 * response
                 * url:要跳转的url 此处不可能固定的跳转到某一个页面，配置可以使用标准登录页还是使用自己写的登录页
                 */
                //redirectStrategy.sendRedirect(request, response,securityProperties.getBrowser().getLoginPage());
                redirectStrategy.sendRedirect(request, response, "login.html");
                //url:
                // 跳转到用户配置的login的配置
            }
        }
        //如果不是一个html请求，返回401状态码和错误信息
        return new SimpleResponse("访问的服务需要身份认证，请引导用户到登录页");
    }

    public String getLoginPage() {
        return "login.html";
    }
}